package cn.edu.ctbu.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;

import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;

public class JWTUtil {

    /**
     * 加盐  目标增加我们token长度
     * */
    private static final String SECRET = "zgz";

    public static String createToken(String username){
        //设置token时间 三小时
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.HOUR, 24);
        Date date = nowTime.getTime();


        //密文生成
        String token = null;
        try {
            token = JWT.create()
                    .withClaim("username", username)  //载荷
                    .withExpiresAt(date)
                    .withIssuedAt(new Date())
                    .sign(Algorithm.HMAC256(SECRET));
        } catch (UnsupportedEncodingException e) {
            System.out.println("创建token失败");
        }
        return token;
    }

    /**
     * 验证token的有效性
     * */
    public static boolean verify(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            verifier.verify(token);
            return true;
        } catch (UnsupportedEncodingException e) {
            return false;
        }
    }

    /**
     * 获取token列名
     * **/
    /**
     * 通过载荷名字获取载荷的值
     * */

    public static String getClaim(String token, String name){
        String claim = null;
        try {
            claim =  JWT.decode(token).getClaim(name).asString();
        }catch (Exception e) {
            return "getClaimFalse";
        }
        return claim;
    }
}
